package com.lagou.task;

import com.alibaba.fastjson.JSON;
import com.lagou.server.ZkProxy;
import com.lagou.service.NodeContentInfo;
import org.apache.curator.framework.CuratorFramework;

/**
 * @author yangpeng
 * @time 2020/5/21
 * @since 1.0.0
 */
public class ZkTask {

    public void clearResponseTime() {
        try {
            System.out.println("========Host：" + ZkProxy.IP + "====Port:" + ZkProxy.PORT + "======开始清理过期时间=========");
            CuratorFramework client = ZkProxy.getClient();
            byte[] data = client.getData().forPath(ZkProxy.ZK_NODE_PATH);
            String result = new String(data);
            System.out.println(result);
            NodeContentInfo nodeInfo = JSON.toJavaObject(JSON.parseObject(new String(data)), NodeContentInfo.class);
            if (nodeInfo.getResponseTime() == 0) {
                return;
            }
            if (nodeInfo.getExpireTime() <= System.nanoTime()) {
                //说明时间过期，将节点数据重置为0
                nodeInfo.setResponseTime(0L);
                nodeInfo.setExpireTime(System.nanoTime() + 5 * 1000 * 1000);
                client.setData().forPath(ZkProxy.ZK_NODE_PATH, JSON.toJSONString(nodeInfo).getBytes());
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}
